import plugin from '../../lib/plugins/plugin.js';
import common from "../../lib/common/common.js";
import fetch from 'node-fetch';
import sharp from 'sharp'
import axios from 'axios';

let maxnum = 10
export class example extends plugin {
    constructor() {
        super({
            name: '识别动漫角色',
            event: 'message',
            priority: 5000,
            rule: [
                {
                    reg: '^#?人物识别$',
                    fnc: 'anime'
                }
            ]

        })
    }
	
	
  async anime(e) {
	let imgurl = await this.getImage(e)
	if (!imgurl) return
	let base64 = await url_to_base64(imgurl)

	let model = 'animetrace_high_beta'
	let url = `https://api.animetrace.com/v1/search`
	let headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67',
        'Content-Type': 'application/json'
    };
	let body = {
        is_multi: 1,
        ai_detect: 1,
        model: model,
        base64: base64
    }

	e.reply(`人物识别中，本次使用模型 ${model}`,false,{ recallMsg: 10 })

	let res = ''
	try {
		let response = await axios.post(url, body, {
            headers: headers
        })
        res = response.data
	} catch(error) {
		e.reply(`请求失败`, true)
		return
	}
	
	if (res.zh_message) {
		e.reply(res.zh_message, true)
		return
	}
	let msgs = []
	    msgs.push(`本次共识别到 ${res.data.length} 位（动漫/游戏）人物`)
	if (res.data.length == 0) {
		e.reply(msgs,true,{ recallMsg: 10 })
		return
	}
	if (res.ai) {
	    msgs.push('该图可能是ai绘图！')
	}
	
	//fs.writeFileSync('./123.json',JSON.stringify(res, null, 2)) 
	// 获取图片尺寸
	let image = await fetch(imgurl);
    let imageBuffer = Buffer.from(await image.arrayBuffer())
    let metadata = await sharp(imageBuffer).metadata();
    let width = metadata.width;
    let height = metadata.height;
	
	for (let shuju of res.data) {
		let data = ''
		let box = shuju.box;
        let left = Math.ceil(box[0] * width);
        let top = Math.ceil(box[1] * height);
        let right = Math.ceil(box[2] * width);
        let bottom = Math.ceil(box[3] * height);
			
	    // 计算裁剪区域的宽度和高度
        let cropWidth = right - left;
        let cropHeight = bottom - top;

        // 裁剪图片并转为 Buffer
        let img = await sharp(imageBuffer)
            .extract({ left, top, width: cropWidth, height: cropHeight })
            .toBuffer();
			
	    for (let i = 0; i < shuju.character.length; i++) {
		    data += `┏ 来源：《${shuju.character[i].work}》\n┗ 人物：${shuju.character[i].character}\n\n`
			if (i >= (maxnum - 1)) break
	    }
		msgs.push([segment.image(img), data])
	}
	await e.reply(await common.makeForwardMsg(e, msgs))
	  
  }
  
  async getImage(e) {
	let imgUrls = []
	  if (e.source || e.reply_id ) {
        // 优先从回复找图
        let reply
        if (this.e.getReply) {
          reply = await this.e.getReply()
        } else if (this.e.source) {
          if (this.e.group?.getChatHistory)
            reply = (await this.e.group.getChatHistory(this.e.source.seq, 1)).pop()
          else if (this.e.friend?.getChatHistory)
            reply = (await this.e.friend.getChatHistory(this.e.source.time, 1)).pop()
        }
        if (reply?.message) {
          for (let val of reply.message) {
            if (val.type === 'image') {
                imgUrls.push(val.url)
            }
          }
        }
      }
	  else if (e.img) {
        // 一起发的图
        imgUrls.push(...e.img)
      }   
	if (imgUrls.length) {
        return imgUrls[0]
	} else {
		return ''
	}
  }
       
}

async function url_to_base64(url) {
        let img = await axios.get(url, {
            responseType: 'arraybuffer'
        });
        let base64 = Buffer.from(img.data, 'binary')
            .toString('base64');
        return base64
    }